package cn.sylinx.horm.proxy.command.interceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import cn.sylinx.horm.interceptor.Invocation;
import cn.sylinx.horm.proxy.command.invoker.CommandInvoker;
import cn.sylinx.horm.util.ClassUtil;

public class CommandInvokerProxy implements InvocationHandler {

    private final CommandInvoker commandInvoker;

    public CommandInvokerProxy(CommandInvoker commandInvoker) {
        this.commandInvoker = commandInvoker;
    }

    public static CommandInvoker create(CommandInvoker commandInvoker) {
        return (CommandInvoker) Proxy.newProxyInstance(ClassUtil.getDefaultClassLoader(),
                new Class<?>[] { CommandInvoker.class }, new CommandInvokerProxy(commandInvoker));
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        }
        return CommandInterceptorManager.INSTANCE.getInterceptor()
                .intercept(new Invocation(commandInvoker, method, args));
    }
}
